<?php
class ReferenceSearcher {

	public $table;
	public $conditionParam;
	public $pageParam;
	
	/**
	 * Constructor initialize variable and call search function
	 *
	 * @return void
	 * @author Elliot Yap
	 */
	public function ReferenceSearcher() {
		
		# table info config
		$this->table = array(
			// set false if dont join
			'tableName'			=> 'reference a',
			'leftTableName'		=> 'album b',
			'leftJoinOn'		=> 'a.album_id=b.id',
			'fieldNames'		=> 'a.id,a.name,a.album_id,a.date_create,a.reference_type_id,a.year,b.artist_id',
			#'hasManyTableName'	=> 'album c',
			'hasManyTableName'	=> false,
			'hasManyKey'		=> 'album_id',
			'hasManyFieldNames'	=> '*',
			'countFieldName'	=> 'a.id',
			'defaultSortCol'	=> 'a.date_create',
			'defaultSortDir'	=> 'desc',
		);
		
		# page param config
		$this->pageParam = Yii::app()->params['paging'];

		# filter config
		$this->conditionParam = array(
			'artist_id' => array(
				'label'	=>'Artist',
				'class' => false,
				'data'	=> Fish::getList('artist','name'),
			),
			'reference_type_id' => array(
				'label'	=> 'Type',
				'class' => false,
				'data'	=> Yii::app()->params['flag']['referenceType'],
			),
			'name' => array(
				'label'	=> 'Name',
				'class' => false,
				'data'	=> false,
			)
		);
	}
	
	/**
	 * Condition Builder
	 *
	 * @return array query_string and query_array for parameterize query builder
	 * @author Elliot Yap
	 */
	public function genQueryCondition($condition) {

		$query_string = array('1=1');
		$query_params = array();
		foreach ($condition as $key => $row) {
			
			switch ($key) {
				case 'datefrom':
					$query_string[] = 'a.`created` > :'.$key.'';
					$query_params[':'.$key] = $row;
				break;
				case 'dateto':
					$query_string[] = 'a.`created` < :'.$key.'';
					$query_params[':'.$key] = $row;
				break;
				case 'user_id': case 'artist_id':
					$query_string[] = $key.'=:'.$key;
					$query_params[':'.$key] = $row;
				break;
				case 'name':
					$query_string[] = 'a.`'.$key.'` LIKE :'.$key;
					$query_params[':'.$key] = '%'.$row.'%';
				break;
				default:
					$query_string[] = '`'.$key.'` LIKE :'.$key;
					$query_params[':'.$key] = '%'.$row.'%';
				break;
			}
		}
		return array(
			'string'=>implode(' AND ',$query_string),
			'params'=>$query_params,
		);
	}
}